package com.agent.rag.service.Impl;

import com.agent.commons.enums.FileType;
import com.agent.commons.exception.BaseException;
import com.agent.commons.other.ThreadLocal;
import com.agent.commons.utils.MinIOUtil;
import com.agent.commons.utils.RabbitMqUtil;
import com.agent.feign.entity.SearchEntity;
import com.agent.rag.client.MilvusClient;
import com.agent.rag.client.SplitterClient;
import com.agent.rag.dataobject.RagPictureDO;
import com.agent.rag.entity.FileActionMessage;
import com.agent.rag.mapper.RagPictureMapper;
import com.agent.rag.service.RagService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import static com.agent.commons.errorcode.ServiceErrorCodeConstants.FILE_NOT_SUPPORT;
import static com.agent.commons.errorcode.ServiceErrorCodeConstants.FILE_UPLOAD_DEFEAT;

@Service
@Slf4j
public class RagServiceImpl implements RagService{

    @Autowired
    private RagPictureMapper ragPictureMapper;
    @Autowired
    private MilvusClient milvusClient;
    /**
     *  rag处理文件
     * @param end 文件后缀
     */
    @Override
    public void actionFile(String end, MultipartFile file) {
        if(!FileType.contains(end)){
            throw new BaseException(FILE_NOT_SUPPORT);
        }
        //对象存储文件上传
        try {
            String fileOriginUrl = MinIOUtil.uploadFile("test-one",
                    file, UUID.randomUUID() + "." + file.getOriginalFilename());
            log.error("文件上传成功：{}",fileOriginUrl);
            FileActionMessage fileActionMessage = new FileActionMessage();
            fileActionMessage.setType(end);
            fileActionMessage.setUrl(fileOriginUrl);
            //从ThreadLocal中获取用户id
            fileActionMessage.setUserId(ThreadLocal.getUserId());
            //发送文件处理消息至消息队列
            RabbitMqUtil.sendMessageDirect("rag.file.direct", fileActionMessage, "action");
        }catch(Exception e){
            throw new BaseException(FILE_UPLOAD_DEFEAT);
        }
    }

    /**
     * 图片存储路径及唯一UUID写入数据库
     * @param fileUrl
     */
    @Override
    public String writePicture(String fileUrl) {
        String uuid = UUID.randomUUID().toString();
        RagPictureDO ragPictureDO = new RagPictureDO();
        ragPictureDO.setPictureUrl(fileUrl);
        ragPictureDO.setPictureId(uuid);
        ragPictureMapper.insert(ragPictureDO);
        return uuid;
    }

    @Override
    public List<SearchEntity> getKnowledge(String text,String userId) {
        return milvusClient.get(text, userId);
    }
}
